package com.ghp.admin.handler;

import com.ghp.auth.exception.AuthException;
import com.ghp.common.exception.BusinessException;
import com.ghp.common.utils.response.ResponseStatus;
import com.ghp.common.utils.response.ResponseResult;
import com.ghp.file.exception.FileException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author ghp
 * @title 全局异常处理器
 * @description 用于捕获Controller层中抛出的异常
 */
@Slf4j
@RestControllerAdvice(annotations = {Controller.class, RestControllerAdvice.class})
public class ControllerExceptionHandler {

    /**
     * 捕获业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult<?> businessExceptionHandler(BusinessException e) {
        log.error("系统执行出错，出现BusinessException异常，异常信息：{} \n {}", e.getMessage(), e.getStackTrace());
        return ResponseResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 捕获第三方授权异常
     */
    @ExceptionHandler(AuthException.class)
    public ResponseResult authExceptionHandler(AuthException e){
        log.error("系统执行出错，出现BusinessException异常，异常信息：{} \n {}", e.getMessage(), e.getStackTrace());
        return ResponseResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 捕获OSS文件存储异常
     */
    @ExceptionHandler(FileException.class)
    public ResponseResult fileExceptionHandler(FileException e){
        log.error("系统执行出错，出现BusinessException异常，异常信息：{} \n {}", e.getMessage(), e.getStackTrace());
        return ResponseResult.fail(e.getMessage());
    }



    /**
     * 捕获唯一性约束异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseResult<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error("执行SQL时出错，出现SQLIntegrityConstraintViolationException异常，异常信息:{} \n {}", e.getMessage(), e.getStackTrace());
        // 给出更加详细的提示信息
        if (e.getMessage().contains("Duplicate entry")) {
            // 截取出重复的name，然后给出提示信息
            String msg = e.getMessage();
            int index = msg.indexOf("Duplicate entry");
            msg = msg.substring(index);
            String[] split = msg.split(" ");
            msg = split[2] + "已存在";
            return ResponseResult.fail(ResponseStatus.SYSTEM_ERROR.getCode(), msg);
        }
        // 其它异常
        return ResponseResult.fail(ResponseStatus.SYSTEM_ERROR);
    }

    /**
     * 捕获参数校验异常
     * 备注：MethodArgumentNotValidException 是在使用校验注解（如 @Valid）对请求参数进行校验时，如果参数校验不通过，会抛出该异常。
     * 该异常通常是由于请求参数不符合预期的约束条件（如非空、长度限制等）导致的
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult exceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数校验出错！出现MethodArgumentNotValidException异常，异常信息： {} \n", e.getMessage(), e.getStackTrace());
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.fail(ResponseStatus.SYSTEM_ERROR.getCode(), message);
    }

    /**
     * 捕获参数校验异常
     * 备注: 处理参数绑定异常，参数类型不正确，比如参数要求是数字，但是当前是字符串，此时抛BindExceptionHandler
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseResult BindExceptionHandler(BindException e) {
        log.error("参数校验出错，出现BindException异常，异常信息：{} \n {}", e.getMessage(), e.getStackTrace());
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.fail(ResponseStatus.SYSTEM_ERROR.getCode(), message);
    }

    /**
     * 捕获参数校验异常
     * 备注：处理参数校验异常，参数校验不合格，比如长度要求1~2，但是参数长度不在这个范围，此时就抛ConstraintViolationException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error("参数校验出错，出现ConstraintViolationException异常，异常信息：{} \n {}", e.getMessage(), e.getStackTrace());
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.fail(ResponseStatus.SYSTEM_ERROR.getCode(), message);
    }

}
